import { EyeOutlined } from '@ant-design/icons';
import { DragSortTable, ProColumnType } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProForm,
  ProFormText,
  ProFormTextArea,
  ProFormDigit,
  BetaSchemaForm,
  ProFormSwitch
} from '@ant-design/pro-components';
import { Card, Col, Form, message, Popconfirm, Row, Image, Button } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import { getSettingList, saveFeeSetting, saveRebateDecrSetting, saveRebateSetting } from './service';
import useStyles from './style.style';
import CustomImgUpload from '@/components/CustomImgUpload';
import CustomEditor from '@/components/CustomRichEditor';
import { useRequest } from '@umijs/max';

interface TableFormDateType {
  key: string;
  workId?: string;
  name?: string;
  department?: string;
  isNew?: boolean;
  editable?: boolean;
}

type InternalNamePath = (string | number)[];

interface ErrorField {
  name: InternalNamePath;
  errors: string[];
}

const AdvancedForm: FC<Record<string, any>> = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm()
  const [rebateAddForm] = Form.useForm()
  const [rebateEditForm] = Form.useForm()
  const [decrRebateAddForm] = Form.useForm()
  const [decrRebateEditForm] = Form.useForm()
  const [, setError] = useState<ErrorField[]>([]);

  const { refresh } = useRequest(getSettingList, {
    onSuccess(data) {
      // console.log(data?.item);
      
      form.setFieldsValue(data?.item)
    },
  });

  const onFinish = async (values: Record<string, any>) => {
    // console.log('values', values);
    
    const hide = message.loading('正在保存');

    try {
      const res = await Promise.all([
        saveFeeSetting({
          fee: values?.fee
        }),
        saveRebateSetting({
          rebate: values?.rebate
        }),
        saveRebateDecrSetting({
          decrRebate: values?.decrRebate
        }),
      ]);
      // console.log(res);
      hide();
      if (res?.every(item => item.code === 0)) {
        message.success('保存成功，即将刷新');
        refresh()
        return true;
      } else {
        message.error('保存失败，请重试');
        return false;
      }
    } catch (error) {
      hide();
      message.error('保存失败，请重试');
      return false;
    }

  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  const rebateColumns: ProColumnType<TableFormDateType>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      valueType: 'digit',
      initialValue: form.getFieldsValue()?.home_grid?.length + 1 || 0,
      width: 120,
    },
    {
      title: '佣金',
      dataIndex: 'fee',
      valueType: 'digit',
      fieldProps: {
        style: {
          width: '100%'
        }
      }
    },
    {
      title: '供应比例',
      dataIndex: 'max',
      valueType: 'digit',
      fieldProps: {
        style: {
          width: '100%',
        },
        // precision: 0,
        addonAfter: '%'
      },
      render(dom, entity: any, index, action, schema) {
        return (entity?.max || '-') + '%'
      },
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record: TableFormDateType,) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            layoutType={'ModalForm'}
            form={rebateEditForm}
            onFinish={async (values) => {
              const companyBanner = form.getFieldsValue()?.company?.banner || []
              const newCompanyBanner = companyBanner.map((item: any) => {
                if (record?.key === item?.key) {
                  // eslint-disable-next-line no-param-reassign
                  item = {
                    ...item,
                    ...values
                  }
                }
                return item
              })

              form.setFieldValue(['company', 'banner'], newCompanyBanner)
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: `编辑 ${record.name} 佣金设置`,
              width: "500px",
            }}
            trigger={<a
              key="eidit"
              onClick={() => {
                rebateEditForm.resetFields()
                rebateEditForm.setFieldsValue(record)
              }}
            >
              编辑
            </a>}
            columns={rebateColumns as any}
          />,
          <Popconfirm
            key="del"
            title="删除"
            description={<>
              <p>确认删除 <b>{record?.name}</b> ?</p>
            </>}
            onConfirm={async () => {
              const companyBanner = (form.getFieldsValue()?.company?.banner || [])?.filter((item: any) => {
                return item?.key !== record?.key
              })
              form.setFieldValue(['rebate'], companyBanner)
              return true
            }}
            okText="是"
            cancelText="否"
          >
            <a
              key="del"
            >
              删除
            </a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const decrRebateColumns: ProColumnType<TableFormDateType>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      valueType: 'digit',
      initialValue: form.getFieldsValue()?.home_grid?.length + 1 || 0,
      width: 120,
    },
    {
      title: '佣金',
      dataIndex: 'fee',
      valueType: 'digit',
      fieldProps: {
        style: {
          width: '100%',
        },
      },
    },
    {
      title: '时间',
      dataIndex: 'max',
      valueType: 'digit',
      fieldProps: {
        style: {
          width: '100%',
        },
        precision: 0,
        addonAfter: '分钟'
      },
      render(dom, entity: any, index, action, schema) {
        return (entity?.max || '-') + '分钟'
      },
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record: TableFormDateType,) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            layoutType={'ModalForm'}
            form={decrRebateEditForm}
            onFinish={async (values) => {
              const companyBanner = form.getFieldsValue()?.company?.banner || []
              const newCompanyBanner = companyBanner.map((item: any) => {
                if (record?.key === item?.key) {
                  // eslint-disable-next-line no-param-reassign
                  item = {
                    ...item,
                    ...values
                  }
                }
                return item
              })

              form.setFieldValue(['decrRebate'], newCompanyBanner)
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: `编辑 ${record.name} 递减佣金设置`,
              width: "500px",
            }}
            trigger={<a
              key="eidit"
              onClick={() => {
                decrRebateEditForm.resetFields()
                decrRebateEditForm.setFieldsValue(record)
              }}
            >
              编辑
            </a>}
            columns={decrRebateColumns as any}
          />,
          <Popconfirm
            key="del"
            title="删除"
            description={<>
              <p>确认删除 <b>{record?.name}</b> ?</p>
            </>}
            onConfirm={async () => {
              const companyBanner = (form.getFieldsValue()?.company?.banner || [])?.filter((item: any) => {
                return item?.key !== record?.key
              })
              form.setFieldValue(['decrRebate'], companyBanner)
              return true
            }}
            okText="是"
            cancelText="否"
          >
            <a
              key="del"
            >
              删除
            </a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const CustomRebateTable = (props: any) => {
    return <DragSortTable
      columns={rebateColumns}
      rowKey="key"
      search={false}
      pagination={false}
      dataSource={props?.value}
      onChange={props?.onChange}
      dragSortKey="sort"
      onDragSortEnd={(
        beforeIndex: number,
        afterIndex: number,
        newDataSource: any,
      ) => {
        // console.log('排序后的数据', newDataSource);
        // message.success('修改列表排序成功');
        form.setFieldValue(['rebate'], newDataSource)
      }}
      toolBarRender={false}
      editable={{}}
    />
  }

  const CustomDecrRebateTable = (props: any) => {
    return <DragSortTable
      columns={decrRebateColumns}
      rowKey="key"
      search={false}
      pagination={false}
      dataSource={props?.value}
      onChange={props?.onChange}
      dragSortKey="sort"
      onDragSortEnd={(
        beforeIndex: number,
        afterIndex: number,
        newDataSource: any,
      ) => {
        // console.log('排序后的数据', newDataSource);
        // message.success('修改列表排序成功');
        form.setFieldValue(['rebate'], newDataSource)
      }}
      toolBarRender={false}
      editable={{}}
    />
  }

  return (
    <ProForm
      layout="vertical"
      form={form}
      submitter={{
        render: (props, dom) => {
          return (
            <FooterToolbar>
              {/*{getErrorInfo(error)}*/}
              {dom}
            </FooterToolbar>
          );
        },
      }}
      initialValues={{}}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    // onValuesChange={(values) => {
    //   console.log(values)
    // }}
    >
      <PageContainer content="公共设置常用于对通用的功能设置">
        <Card title="基本设置" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormDigit
                label={'手续费'}
                name={'fee'}
                // rules={[
                //   {
                //     message: '请输入手续费',
                //   },
                // ]}
                placeholder="请输入手续费"
              />
            </Col>
          </Row>
        </Card>

        <Card title="佣金设置" className={styles.card} bordered={false}>
          <BetaSchemaForm<any>
            key="primary"
            form={rebateAddForm}
            layoutType={'ModalForm'}
            onFinish={async (values) => {
              const companyBanner = form.getFieldsValue()?.rebate || []
              companyBanner.push({
                ...values,
                key: companyBanner?.length + 1 || 0,
              })
              form.setFieldValue(['rebate'], [...companyBanner])
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: "新增佣金设置",
              width: "500px",
            }}
            trigger={<Button style={{ marginBottom: 20 }} onClick={() => {
              const companyBanner = form.getFieldsValue()?.rebate || []
              rebateAddForm.setFieldValue('sort', companyBanner?.length || 0)
            }}>新增</Button>}
            columns={rebateColumns as any}
          />
          <ProForm.Item name={['rebate']}>
            <CustomRebateTable />
          </ProForm.Item>
        </Card>

        <Card title="递减佣金设置" className={styles.card} bordered={false}>
          <BetaSchemaForm<any>
            key="primary"
            form={decrRebateAddForm}
            layoutType={'ModalForm'}
            onFinish={async (values) => {
              const companyBanner = form.getFieldsValue()?.decrRebate || []
              companyBanner.push({
                ...values,
                key: companyBanner?.length + 1 || 0,
              })
              form.setFieldValue(['decrRebate'], [...companyBanner])
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: "新增递减佣金设置",
              width: "500px",
            }}
            trigger={<Button style={{ marginBottom: 20 }} onClick={() => {
              const companyBanner = form.getFieldsValue()?.decrRebate || []
              rebateAddForm.setFieldValue('sort', companyBanner?.length || 0)
            }}>新增</Button>}
            columns={decrRebateColumns as any}
          />
          <ProForm.Item name={['decrRebate']}>
            <CustomDecrRebateTable />
          </ProForm.Item>
        </Card>
      </PageContainer>
    </ProForm>
  );
};
export default AdvancedForm;
